import 'dart:ffi';
import 'dart:io';

import 'package:android_tool/page/common/app.dart';
import 'package:android_tool/widget/text_view.dart';
import 'package:desktop_drop/desktop_drop.dart';
import 'package:dotted_border/dotted_border.dart';
import 'package:file_selector/file_selector.dart';
import 'package:flutter/material.dart';
import 'package:flutter_list_view/flutter_list_view.dart';
import 'package:process_run/shell_run.dart';
import 'package:provider/provider.dart';
import 'package:substring_highlight/substring_highlight.dart';

import '../common/base_page.dart';
import '../common/icon_font.dart';
import 'batch_view_model.dart';

class AdbBatch extends StatefulWidget {
  final String adbPath;

  const AdbBatch(this.adbPath, {Key? key}) : super(key: key);

  @override
  State<AdbBatch> createState() => _AdbBatchState();
}

class _AdbBatchState extends BasePage<AdbBatch, BatchManagerViewModel> {
  final AdbBatchController adbBatchcontroller = AdbBatchController();

  @override
  void initState() {
    super.initState();
    viewModel.init();
  }

  @override
  Widget contentView(BuildContext context) {
    return ChangeNotifierProvider.value(
        value: adbBatchcontroller,
        builder: (context, child) {
          return Container(
            padding: const EdgeInsets.symmetric(horizontal: 50, vertical: 30),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: <Widget>[
                    buttonView(
                      IconFont.install,
                      "批量安装应用",
                      () {
                        viewModel.install();
                      },
                    ),
                    buttonView(
                      IconFont.rerun,
                      "批量重启",
                      () {
                        viewModel.reboot();
                      },
                    ),
                    buttonView(
                      IconFont.input,
                      "批量卸载应用",
                      () {
                        viewModel.uninstallApk();
                      },
                    ),
                    const TextView("卸载包名："),
                    Expanded(
                      child: Container(
                        height: 33,
                        alignment: Alignment.centerLeft,
                        padding: const EdgeInsets.symmetric(horizontal: 8),
                        // decoration: BoxDecoration(
                        //   border: Border.all(color: Colors.grey),
                        //   borderRadius: BorderRadius.circular(5),
                        // ),
                        child: TextField(
                          controller: viewModel.uninstallPackage,
                          decoration: const InputDecoration(
                            contentPadding: EdgeInsets.symmetric(
                                vertical: 0, horizontal: 8),
                            hintText: "请输入卸载软件包名",
                            border: OutlineInputBorder(),
                            hintStyle: TextStyle(fontSize: 14),
                          ),
                          style: const TextStyle(fontSize: 14),
                        ),
                      ),
                    ),
                  ],
                ),

                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: <Widget>[
                    buttonView(
                      IconFont.clean,
                      "批量删除文件",
                      () {
                        viewModel.deleteFile();
                      },
                    ),
                    const TextView("绝对路径："),
                    Expanded(
                      child: Container(
                        height: 33,
                        alignment: Alignment.centerLeft,
                        padding: const EdgeInsets.symmetric(horizontal: 8),
                        // decoration: BoxDecoration(
                        //   border: Border.all(color: Colors.grey),
                        //   borderRadius: BorderRadius.circular(5),
                        // ),
                        child: TextField(
                          controller: viewModel.deleteFilePath,
                          decoration: const InputDecoration(
                            contentPadding: EdgeInsets.symmetric(
                                vertical: 0, horizontal: 8),
                            hintText: "请输入删除文件路径",
                            border: OutlineInputBorder(),
                            hintStyle: TextStyle(fontSize: 14),
                          ),
                          style: const TextStyle(fontSize: 14),
                        ),
                      ),
                    ),
                    //------------------------------------------adb 指令
                    buttonView(
                      IconFont.start,
                      "批量执行adb指令",
                          () {
                        viewModel.excuteAdbCmd();
                      },
                    ),
                    const TextView("指令："),
                    Expanded(
                      child: Container(
                        height: 33,
                        alignment: Alignment.centerLeft,
                        padding: const EdgeInsets.symmetric(horizontal: 8),
                        // decoration: BoxDecoration(
                        //   border: Border.all(color: Colors.grey),
                        //   borderRadius: BorderRadius.circular(5),
                        // ),
                        child: TextField(
                          controller: viewModel.excuAdbCmd,
                          decoration: const InputDecoration(
                            contentPadding: EdgeInsets.symmetric(
                                vertical: 0, horizontal: 8),
                            hintText: "请输入adb指令",
                            border: OutlineInputBorder(),
                            hintStyle: TextStyle(fontSize: 14),
                          ),
                          style: const TextStyle(fontSize: 14),
                        ),
                      ),
                    ),
                    //------------------------------------------shell 指令
                    buttonView(
                      IconFont.exCmd,
                      "批量执行shell指令",
                      () {
                        viewModel.excuteShellCmd();
                      },
                    ),
                    const TextView("指令："),
                    Expanded(
                      child: Container(
                        height: 33,
                        alignment: Alignment.centerLeft,
                        padding: const EdgeInsets.symmetric(horizontal: 8),
                        // decoration: BoxDecoration(
                        //   border: Border.all(color: Colors.grey),
                        //   borderRadius: BorderRadius.circular(5),
                        // ),
                        child: TextField(
                          controller: viewModel.excuCmd,
                          decoration: const InputDecoration(
                            contentPadding: EdgeInsets.symmetric(
                                vertical: 0, horizontal: 8),
                            hintText: "请输入shell指令(不需要输入shell)",
                            border: OutlineInputBorder(),
                            hintStyle: TextStyle(fontSize: 14),
                          ),
                          style: const TextStyle(fontSize: 14),
                        ),
                      ),
                    ),
                  ],
                ),
                const SizedBox(
                  height: 10,
                ),
                const SizedBox(
                  height: 10,
                ),
                DottedBorder(
                  borderType: BorderType.RRect,
                  radius: const Radius.circular(12),
                  color: Colors.black12,
                  dashPattern: const [4, 2],
                  child: ClipRRect(
                    borderRadius: const BorderRadius.all(Radius.circular(12)),
                    child: DropTarget(
                        onDragDone: (details) async {
                          var path = details.files.first.path;
                          print("file path:${path}");
                          var deviceFile = File(details.files.first.path);
                          String contents = await deviceFile.readAsString();
                          print("file content:${contents}");
                          List<String> deviceIps = contents.split('\n');
                          print("设备数:${deviceIps.length}");
                          viewModel.addDeviceByIpFIle(deviceIps);
                        },
                        child: InkWell(
                          onTap: () {
                            viewModel.selIpFile();
                          },
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            children: const [
                              SizedBox(height: 10),
                              Center(
                                child: Icon(
                                  Icons.insert_drive_file,
                                  color: Colors.grey,
                                  size: 25,
                                ),
                              ),
                              SizedBox(height: 10),
                              TextView(
                                "请将设备IP文件拖拽到此处",
                                color: Colors.grey,
                              ),
                              SizedBox(height: 15),
                            ],
                          ),
                        )
                        // child: Column(
                        //   mainAxisSize: MainAxisSize.min,
                        //   children: const [
                        //     SizedBox(height: 10),
                        //     Center(
                        //       child: Icon(
                        //         Icons.insert_drive_file,
                        //         color: Colors.grey,
                        //         size: 25,
                        //       ),
                        //     ),
                        //     SizedBox(height: 10),
                        //     TextView(
                        //       "请将设备IP文件拖拽到此处",
                        //       color: Colors.grey,
                        //     ),
                        //     SizedBox(height: 15),
                        //   ],
                        // ),
                        ),
                  ),
                ),
                const SizedBox(height: 20),
                MaterialButton(
                  height: 45,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10),
                  ),
                  color: Colors.blue,
                  minWidth: double.infinity,
                  onPressed: () async {
                    viewModel.connectDevices();
                  },
                  child: const TextView(
                    "通过IP文件连接安卓设备",
                    color: Colors.white,
                  ),
                ),
                const SizedBox(height: 20),
                Row(
                  children: [
                    const SizedBox(width: 16),
                    const TextView("网段："),
                    Expanded(
                      child: Container(
                        height: 33,
                        alignment: Alignment.centerLeft,
                        padding: const EdgeInsets.symmetric(horizontal: 8),
                        // decoration: BoxDecoration(
                        //   border: Border.all(color: Colors.grey),
                        //   borderRadius: BorderRadius.circular(5),
                        // ),
                        child: TextField(
                          controller: viewModel.segment,
                          decoration: const InputDecoration(
                            contentPadding: EdgeInsets.symmetric(
                                vertical: 0, horizontal: 8),
                            hintText: "请输入网段",
                            border: OutlineInputBorder(),
                            hintStyle: TextStyle(fontSize: 14),
                          ),
                          style: const TextStyle(fontSize: 14),
                        ),
                      ),
                    ),
                    const SizedBox(width: 16),
                    const TextView("端口："),
                    Expanded(
                      child: Container(
                        height: 33,
                        alignment: Alignment.centerLeft,
                        padding: const EdgeInsets.symmetric(horizontal: 8),
                        // decoration: BoxDecoration(
                        //   border: Border.all(color: Colors.grey),
                        //   borderRadius: BorderRadius.circular(5),
                        // ),
                        child: TextField(
                          controller: viewModel.port,
                          decoration: const InputDecoration(
                            contentPadding: EdgeInsets.symmetric(
                                vertical: 0, horizontal: 8),
                            hintText: "请输入端口",
                            border: OutlineInputBorder(),
                            hintStyle: TextStyle(fontSize: 14),
                          ),
                          style: const TextStyle(fontSize: 14),
                        ),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 20),
                Container(
                  width: double.infinity, // 使容器的宽度占满父容器
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start, // 子元素之间平均分配空间
                    children: [
                      MaterialButton(
                        height: 45,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10),
                        ),
                        color: Colors.blue,
                        onPressed: () async {
                          viewModel.scanAllInLanAndroidDevices();
                        },
                        child: const TextView(
                          "扫描局域网内安卓设备,自动连接",
                          color: Colors.white,
                        ),
                      ),
                      SizedBox(width: 20, height: 0),
                      MaterialButton(
                        height: 45,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10),
                        ),
                        color: Colors.blue,
                        onPressed: () async {
                          viewModel.findAllConnectAdbDevices();
                        },
                        child: const TextView(
                          "刷新设备",
                          color: Colors.white,
                        ),
                      ),
                      const Spacer(), // 添加的 Spacer 小部件
                      Container(
                        child: Consumer<BatchManagerViewModel>(
                            builder: (context, viewModel, child) {
                          return Text(
                            '已连接设备数量:${viewModel.findDevices.length}', // 你要添加的文本
                            style: TextStyle(
                              color: Colors.black, // 文本颜色可根据需要调整
                            ),
                          );
                        }),
                        // child: Text(
                        //   '已连接设备数量:${ viewModel.findDevices.length}', // 你要添加的文本
                        //   style: TextStyle(
                        //     color: Colors.black, // 文本颜色可根据需要调整
                        //   ),
                        // ),
                      )
                    ],
                  ),
                ),
                //设备列表
                const SizedBox(height: 10),
                _buildLogContentView(),
              ],
            ),
          );
        });
  }

  @override
  createViewModel() {
    return BatchManagerViewModel(context);
  }

  Expanded _buildLogContentView() {
    List<String> aaa = ["192.1", "235"];
    print("${viewModel.findDevices}");
    return Expanded(
      child: Container(
        color: const Color(0xFFF0F0F0),
        child: Consumer<BatchManagerViewModel>(
          builder: (context, viewModel, child) {
            return FlutterListView(
              controller: viewModel.scrollController,
              delegate: FlutterListViewDelegate(
                (context, index) {
                  var devices = viewModel.findDevices[index];
                  Color textColor = Colors.red;
                  return Column(
                    children: [
                      // 分割线
                      Divider(),
                      Row(
                        children: [
                          // 第一列：设备名称
                          Expanded(
                            child: Container(
                              padding: const EdgeInsets.symmetric(
                                  vertical: 3, horizontal: 15),
                              child: SubstringHighlight(
                                text: devices.ip,
                                textStyle: TextStyle(
                                  color: textColor,
                                ),
                                textStyleHighlight: TextStyle(
                                  color: Colors.white,
                                  backgroundColor: devices.isConnect == "已连接"
                                      ? Colors.green
                                      : Colors.red,
                                  fontWeight: FontWeight.bold,
                                ),
                                term: devices.ip,
                              ),
                            ),
                          ),
                          // 分割线
                          VerticalDivider(),
                          // 第二列：连接状态（示例数据，请根据实际情况替换）
                          Expanded(
                            child: Container(
                              padding: const EdgeInsets.symmetric(
                                  vertical: 3, horizontal: 15),
                              child: SubstringHighlight(
                                text: devices.isConnect,
                                textStyle: TextStyle(
                                  color: Colors.green,
                                ),
                                term: devices.isConnect,
                              ),
                            ),
                          ),
                          // 分割线
                          VerticalDivider(),
                          // 第三列：当前状态（示例数据，请根据实际情况替换）
                          Expanded(
                            child: Container(
                              padding: const EdgeInsets.symmetric(
                                  vertical: 3, horizontal: 15),
                              child: SubstringHighlight(
                                text: devices.status,
                                textStyle: TextStyle(
                                  color: Colors.blue,
                                ),
                                term: "Active",
                              ),
                            ),
                          ),
                        ],
                      ),
                    ],
                  );
                },
                childCount: viewModel.findDevices.length,
              ),
            );
          },
        ),
      ),
    );
  }

  Widget buttonView(IconData icon, String title, Function() onPressed) {
    Color color = Colors.blue;
    return Expanded(
      child: InkWell(
        borderRadius: BorderRadius.circular(10),
        onTap: onPressed,
        child: Container(
          padding: const EdgeInsets.all(10.0),
          margin: const EdgeInsets.all(2.0),
          decoration: BoxDecoration(
            color: Colors.blue.withOpacity(0.1),
            borderRadius: BorderRadius.circular(10),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Container(
                width: 40,
                height: 40,
                padding: const EdgeInsets.all(5),
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(5),
                    gradient: LinearGradient(
                      colors: [
                        color.withOpacity(0.5),
                        color.withOpacity(1),
                      ],
                      begin: Alignment.topLeft,
                      end: Alignment.bottomRight,
                    )),
                child: SizedBox(
                  child: Icon(
                    icon,
                    color: Colors.white,
                  ),
                ),
              ),
              const SizedBox(height: 5),
              TextView(
                title,
              )
            ],
          ),
        ),
      ),
    );
    // return Expanded(
    //   child: Padding(
    //     padding: const EdgeInsets.all(8.0),
    //     child: MaterialButton(
    //       height: 45,
    //       color: Colors.blue,
    //       onPressed: onPressed,
    //       shape: RoundedRectangleBorder(
    //         borderRadius: BorderRadius.circular(10.0),
    //       ),
    //       child: ,
    //     ),
    //   ),
    // );
  }
}

class AdbBatchController extends ChangeNotifier {
  final TextEditingController textController = TextEditingController();

  String segment = "";
  String port = "";
  List<String> deviceIps = [];

  String resultText = "";
  Color resultColor = Colors.black38;

  Future<bool> testAdb() async {
    if (textController.text.isEmpty) {
      resultText = "请先选择或输入ADB路径";
      resultColor = Colors.red;
      notifyListeners();
      return false;
    }
    try {
      var result = await Shell()
          .runExecutableArguments(textController.text, ["version"]);
      if (result.exitCode != 0 || result.outLines.isEmpty) {
        resultText = "请确认ADB路径是否正确";
        resultColor = Colors.red;
        notifyListeners();
        return false;
      }
      resultText = result.outText;
      resultColor = Colors.green;
      notifyListeners();
      return true;
    } catch (e) {
      resultText = "请确认ADB路径是否正确";
      resultColor = Colors.red;
      notifyListeners();
      return false;
    }
  }

  Future<void> save(BuildContext context) async {
    if (await testAdb()) {
      await App().setAdbPath(textController.text);
    }
  }
}
